<template>
  <div>
    5x5
  </div>
</template>

<script>
export default {

  created () {
    // this.s5x5_print_grid()
    const grid = [
      [0, 0, 0, 3, 0],
      [0, 0, 0, 4, 0],
      [0, 4, 1, 0, 0],
      [0, 2, 5, 0, 0],
      [1, 0, 0, 0, 5]
    ]
    if (this.s5x5_solve_sudoku(grid)) {
      this.s5x5_print_grid(grid)
    }
  },
  methods: {
    s5x5_print_grid (arr) {
      for (const i of [0, 1, 2, 3, 4]) {
        let str = ''
        for (const j of [0, 1, 2, 3, 4]) {
          // # 注意，在py3.x中，print函数默认都有换行
          // print(arr[i][j], end=""arr[i][j]
          // console.log(arr[i][j])
          str = str + '' + arr[i][j]
        }
        console.log(str)
      }
    },
    s5x5_find_empty_location (arr, l) {
      for (const row of [0, 1, 2, 3, 4]) {
        for (const col of [0, 1, 2, 3, 4]) {
          if (arr[row][col] === 0) {
            l[0] = row
            l[1] = col
            // # print("empty: row="+str(row)+" col="+str(col))
            return true
          }
        }
      }
      return false
    },
    s5x5_used_in_row (arr, row, num) {
      for (const i of [0, 1, 2, 3, 4]) {
        if (arr[row][i] === num) {
          return true
        }
      }
      return false
    },
    s5x5_used_in_col (arr, col, num) {
      for (const i of [0, 1, 2, 3, 4]) {
        if (arr[i][col] === num) {
          return true
        }
      }
      return false
    },
    s5x5_check_location_is_safe (arr, row, col, num) {
      return (!this.s5x5_used_in_row(arr, row, num) && !this.s5x5_used_in_col(arr, col, num))
    },
    s5x5_solve_sudoku (arr) {
      // # 当前搜索的第几行、第几列
      const l = [0, 0]
      // # 找出还未被填充的位置
      if (!this.s5x5_find_empty_location(arr, l)) {
        return true
      }
      // # 未被填充的位置，赋值给row，col
      const row = l[0]
      const col = l[1]
      for (const num of [1, 2, 3, 4, 5]) {
        // # 找出还未被填充的位置
        if (this.s5x5_check_location_is_safe(arr, row, col, num)) {
          arr[row][col] = num
          // #s5x5_print_grid(arr)
          if (this.s5x5_solve_sudoku(arr)) {
            return true
          }
          arr[row][col] = 0
        }
      }
      return false
    }
  }

}
</script>

<style>

</style>
